Learn T-SQL Commands with Samples
Skip Navigation Links
Skip Navigation Links.
Expand DatabaseDatabase
Expand TableTable
Expand ViewView
Expand Stored ProcedureStored Procedure
Expand Data FilteringData Filtering
Expand Data GroupingData Grouping
Expand JoinsJoins
Expand TriggerTrigger
Expand CursorCursor
Expand OperatorsOperators
Expand ConstraintsConstraints
Expand FunctionsFunctions
Expand Conditional ProcessingConditional Processing
Expand LoopingLooping
Expand Error HandlingError Handling
Collapse v.IMP Queriesv.IMP Queries
Expand XMLXML
Expand Query PerformanceQuery Performance
Expand QueriesQueries
Expand NormalizationNormalization
Expand CreateCreate
     

Find Max, Min Values in a Row

 

      
tblVal
ID V1 V2 V3
1 20 10 30
2 50 60 40
3 90 80 70
SELECT * FROM tblVal as a CROSS APPLY ( SELECT MAX(unpvt.[value]) as Max_Value, MIN(unpvt.[value]) as Min_Value FROM (SELECT t.ID, t.v1 as [1], t.v2 as [2], t.v3 as [3] FROM tblVal as t WHERE t.ID = a.ID) as pvt UNPIVOT ([value] FOR [col] in ([1], [2], [3])) as unpvt GROUP BY unpvt.ID ) as b
Output
ID V1 V2 V3 Max_Value Min_Value
1 20 10 30 30 10
2 50 60 40 60 40
3 90 80 70 90 70